package difficult;

import java.util.Map;

public class Solution_124 {

    private int rst;

    public int maxPathSum(TreeNode root) {
        rst = Integer.MIN_VALUE;
        dps(root);
        return rst;
    }

    private int dps(TreeNode node) {
        int temp = node.val, left = Integer.MIN_VALUE, right = Integer.MIN_VALUE;
        if (node.left != null) {
            left = dps(node.left);
        }
        if (node.right != null) {
            right = dps(node.right);
        }
        int num = temp + Math.max(left, 0) + Math.max(right, 0);
        rst = Math.max(Math.max(Math.max(left, right), num), rst);
        return temp + Math.max(Math.max(left, 0), Math.max(right, 0));
    }

    public static void main(String[] args) {
        Solution_124 model = new Solution_124();
        TreeNode root = new TreeNode(-10);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

//        TreeNode root = new TreeNode(1);
//        root.left = new TreeNode(2);
//        root.right = new TreeNode(3);


//        TreeNode root = new TreeNode(5);
//        root.left = new TreeNode(4);
//        root.left.left = new TreeNode(11);
//        root.left.left.left = new TreeNode(7);
//        root.left.left.right = new TreeNode(2);
//        root.right = new TreeNode(8);
//        root.right.left = new TreeNode(13);
//        root.right.right = new TreeNode(4);
//        root.right.right.right = new TreeNode(1);
        System.out.println(model.maxPathSum(root));
    }

    static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
}
